package com.cssy.yd.logic.web;


import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONArray;
import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.yd.basic.entity.BasicCompanyDO;
import com.cssy.yd.basic.entity.BasicModePaymentDO;
import com.cssy.yd.basic.service.IBasicCompanyService;
import com.cssy.yd.logic.entity.LogicFkDO;
import com.cssy.yd.logic.entity.LogicFkItemDO;
import com.cssy.yd.logic.entity.LogicPoDO;
import com.cssy.yd.logic.entity.LogicPoItemDO;
import com.cssy.yd.logic.entity.LogicSkItemDO;
import com.cssy.yd.logic.entity.LogicSoWareDO;
import com.cssy.yd.logic.entity.LogicSkDO;
import com.cssy.yd.logic.entity.LogicSoWareItemDO;
import com.cssy.yd.logic.service.ILogicSkService;
import com.cssy.yd.logic.service.ILogicSoWareItemService;
import com.cssy.yd.logic.service.ILogicSoWareService;
import com.cssy.yd.logic.util.ToRmbUtil;
import com.cssy.yd.basic.service.IBasicModePaymentService;
import com.plat.exception.SyBaseException;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.SessionUtil;
import com.plat.util.json.AjaxUtil;
import com.plat.util.json.OutJsonGrid;
import com.yuendong.sy.exception.SyCodeException;

@Controller
@RequestMapping("/yd/logic/sk")
public class SkController extends BaseController<LogicSkDO> {
	private static final Logger logger = Logger.getLogger(SkController.class);
	private static final String MANAGER = "/yd/logic/sk/SKManager";// 列表页面
	private static final String EIDT = "/yd/logic/sk/SkOperation";// 添加、修改、显示页面
	

	
	@Resource(name = "logicSkService")
	private ILogicSkService logicSkService;
	
	@Resource(name = "logicSoWareService")
	private ILogicSoWareService logicSoWareService;
	
	@Resource(name = "logicSoWareItemService")
	private ILogicSoWareItemService logicSoWareItemService;
	
	@Resource(name="basicCompanyService")
	private IBasicCompanyService basicCompanyService;
	
	@Resource(name = "basicModePaymentService")
	private IBasicModePaymentService basicModePaymentService;


	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		return MANAGER;
	}

	
	
	@Override
	public void list(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JqGridHandler hander=new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		hander.getWheres(scs);
		String spCode =request.getParameter("spCode");
		String pid =request.getParameter("pid");
		if(StringUtils.isNotEmpty(spCode)){
			scs.addCondition("spcode", spCode, SearchCondition.OP_EQUAL);
		}else if(pid!=null&&!"".equals(pid)){
			scs.addCondition("spcode", pid,SearchCondition.OP_EQUAL);
		}
		String billStatus = request.getParameter("billStatus");
		if(StringUtils.isNotEmpty(billStatus)){
			if(StringUtils.equals(billStatus, "0"))
				scs.addCondition("billstatus", Integer.parseInt(billStatus), "=");	
			else
				scs.addCondition("billstatus", Integer.parseInt("0"),"!=");
		}
		
		scs.setOrderBy("dctime desc");
		SearchResult result= logicSkService.findListByExample(scs);
		OutJsonGrid out=new OutJsonGrid(result);
		out.printJSon(response);
	}
	
	@RequestMapping("/sklist")
	@ResponseBody
	public LogicSkDO warelist(HttpServletRequest request, Model model)
			throws Exception {
		String id=request.getParameter("id"); //logic_so_ware.id
		String oricode=request.getParameter("oricode");   //销售出库单号
		LogicSoWareDO soware = null;
		Double yshk = null;
		Double money = Double.parseDouble("0.0");
		
		List<LogicSoWareItemDO> sowareItem=null;
		SearchConditions scs = new SearchConditions();
		scs.addCondition("billstatus", "2", SearchCondition.OP_EQUAL);
		scs.addCondition("oricode", oricode, SearchCondition.OP_EQUAL);
		
		LogicSkDO skDO = new LogicSkDO();
		try{
			sowareItem=logicSoWareItemService.findItemListBysowareId(id); //按销售出库单id查询SoWareItemDO
			for(LogicSoWareItemDO soitem : sowareItem) {  //遍历出库单item得到收款单的总货款
				BigDecimal money1 = (soitem.getProdPriceWithTax()==null? new BigDecimal("0.0"):soitem.getProdPriceWithTax()).multiply(new BigDecimal(soitem.getProdBSfquantity()==null?new Double("0.0"):soitem.getProdBSfquantity()));
				money = new BigDecimal(money.toString()).add(money1).doubleValue(); //总货款（money)
			}
			soware=  logicSoWareService.findListById(id);
			yshk = logicSkService.findLastedDOByExample(scs); //最近一次收款后的收款单的已收金额
			skDO.setSpCode(soware.getCliNo());
			skDO.setSpName(soware.getCliName());
			skDO.setCurrency(soware.getCurrency());
			skDO.setExchange_rate(soware.getExchangeRate().toString());
			if(yshk != null&&!"".equals(yshk) ){
				skDO.setYshk(yshk);
			} else {
				skDO.setYshk(Double.parseDouble("0.0"));
			}
			if(money != null&&!"".equals(money) ){
				skDO.setMoney(money);
			} else {
				skDO.setMoney(Double.parseDouble("0.0"));
			}
		 } catch(Exception e) {
			 e.printStackTrace();
			 logger.error(e.getMessage(), e);
		 }		
		
		 return skDO;
	}
	
	@RequestMapping("/skitemlist")
	public void skitemlist(HttpServletRequest request, HttpServletResponse response, Model model)
			throws Exception {
		String id=request.getParameter("id"); //销售出库单id，等于logic_so_ware_item.soware_id，logic_so_ware.id
		String oricode=request.getParameter("oricode");   //销售出库单号
		List<LogicSoWareItemDO> soItem=null;
		List<LogicSkItemDO> skitem = new ArrayList<LogicSkItemDO>();
		List<LogicSkDO> historysk = new ArrayList<LogicSkDO>();

		if(id!=null&&!"".equals(id)){
			soItem=logicSoWareItemService.findItemListBysowareId(id);
		}
		
		if(oricode!=null&&!"".equals(oricode)) {	
			SearchConditions scs = new SearchConditions();
			SearchResult sr = new SearchResult();
			scs.addCondition("oricode", oricode, SearchCondition.OP_EQUAL);
			scs.addCondition("billstatus","2", SearchCondition.OP_EQUAL);
			
			//查找对应的所有历史收款单 按销售出货单(oricode)及单据状态为完结的(billstatus=2)来查
			sr = logicSkService.findListByExample(scs);
			if(sr.getRecordCount()>0){ //有收款记录
				historysk = sr.getResults();
				for (LogicSoWareItemDO si : soItem) {
					BigDecimal tempyshk = new BigDecimal("0.0");
					Double yshk = Double.parseDouble("0.0");
					Double wshk = Double.parseDouble("0.0");
					LogicSkItemDO li = new LogicSkItemDO();
					li.setBatch(si.getProdBatch());
					li.setCode(si.getProdNo());
					li.setName(si.getProdName());
					li.setStatus(si.getStatus());
					li.setUnit(si.getProdUnit());
					li.setSpec(si.getProdSpecDesc());
					li.setSourceBillType(si.getSourceBillType());
					li.setQuantity(si.getProdBSfquantity());
					li.setTax_price(si.getProdPriceWithTax()==null? new BigDecimal("0.0"):si.getProdPriceWithTax());
					li.setMoney((si.getProdPriceWithTax()==null? new BigDecimal("0.0"):si.getProdPriceWithTax()).multiply(new BigDecimal(si.getProdBSfquantity()==null?new Double("0.0"):si.getProdBSfquantity())).doubleValue());
					for(LogicSkDO hissk : historysk) { //历史收款单循环
						SearchConditions scs1 = new SearchConditions();
						SearchResult sr1 = new SearchResult();
						scs1.setRemovedProperty(null);
						scs1.addCondition("soid", hissk.getId(), SearchCondition.OP_EQUAL);
						scs1.addCondition("batch", li.getBatch(), SearchCondition.OP_EQUAL);
						scs1.addCondition("source_bill_type", li.getSourceBillType(), SearchCondition.OP_EQUAL);
						scs1.addCondition("code",li.getCode(), SearchCondition.OP_EQUAL); 
						scs1.addCondition("status",li.getStatus(), SearchCondition.OP_EQUAL); 
						sr1 = logicSkService.findItemListByExample(scs1);  //查找此物料的历史收款记录
						if(sr1.getRecordCount()>0){
							List<LogicSkItemDO> hislist = sr1.getResults();
							LogicSkItemDO hisitemdo = hislist.get(0);
							tempyshk = tempyshk.add(new BigDecimal(hisitemdo.getSshk().toString())); 
							wshk = new BigDecimal(li.getMoney().toString()).subtract(tempyshk).doubleValue();
							yshk = tempyshk.doubleValue();
						}else if(sr1.getRecordCount()==0){
							wshk = new BigDecimal(li.getMoney().toString()).subtract(tempyshk).doubleValue();
							yshk = tempyshk.doubleValue();
						}
					}
					li.setYshk(yshk);
					li.setWshk(wshk);
					li.setSshk(Double.parseDouble("0.0"));
					skitem.add(li);
				}
				
			 }else { //没有历史收款记录，第一次新增收款单
				for (LogicSoWareItemDO si : soItem) {
					LogicSkItemDO li = new LogicSkItemDO();
					li.setBatch(si.getProdBatch());
					li.setCode(si.getProdNo());
					li.setName(si.getProdName());
					li.setStatus(si.getStatus());
					li.setUnit(si.getProdUnit());
					li.setSpec(si.getProdSpecDesc());
					li.setSourceBillType(si.getSourceBillType());
					li.setQuantity(si.getProdBSfquantity());
					li.setTax_price(si.getProdPriceWithTax()==null? new BigDecimal("0.0"):si.getProdPriceWithTax());
					li.setMoney((si.getProdPriceWithTax()==null? new BigDecimal("0.0"):si.getProdPriceWithTax()).multiply(new BigDecimal(si.getProdBSfquantity()==null?new Double("0.0"):si.getProdBSfquantity())).doubleValue());
					li.setYshk(Double.parseDouble("0.0"));
					li.setSshk(Double.parseDouble("0.0"));
					li.setWshk(li.getMoney());
					skitem.add(li);
				}
			}
		}
		SearchResult result =new SearchResult();
		result.setResults(skitem);
		result.setRecordCount(skitem.size());
		OutJsonGrid out=new OutJsonGrid(result);
		out.printJSon(response);
	}

	@Override
	public String operationForm(HttpServletRequest request,
			@PathVariable String id, @PathVariable String flag, Model model)
			throws Exception {
		/*SearchConditions scs1 = new SearchConditions();
		scs1.addCondition("parentname", "客户",SearchCondition.OP_EQUAL);
		scs1.setOrderBy("code");
		List<BasicCompanyDO> companyDOs = basicCompanyService.findListByExample(scs1).getResults();*/
		if (OperationFlag.ADD.equals(flag)) {// 新增单据时操作
			model.addAttribute("flag", "ADD");
			SearchConditions scs = new SearchConditions();
			scs.addCondition("cli_no", id, SearchCondition.OP_EQUAL);
			scs.addCondition("paymentStatus", "0,1", SearchCondition.OP_IN);
			scs.addCondition("billstatus", "2", SearchCondition.OP_EQUAL);
			SearchResult sr = logicSoWareService.findListByExample(scs);
			List<LogicSoWareDO> lpwd= sr.getResults();
			 model.addAttribute("lpwd", lpwd);
			 model.addAttribute("xx", 1);
			 model.addAttribute("pid", id);
			 
			 //查询付款方式
			 SearchConditions scs2 = new SearchConditions();
			 scs2.setRemovedProperty(null);
			 SearchResult result1 = basicModePaymentService.findListByExample(scs2);
			 List<BasicModePaymentDO> mp = result1.getResults();
			 model.addAttribute("payment", mp);
		} else {
			LogicSkDO lpd =logicSkService.findListById(id);
			//List<LogicSkItemDO> skitemlist=logicSkService.findItemListBysoid(lpd.getId());
			model.addAttribute("sk", lpd);
			model.addAttribute("flag", lpd.getBillStatus());
			//model.addAttribute("skitemlist", skitemlist);
			model.addAttribute("pid", lpd.getSpCode());
			
			if(lpd.getBillStatus()==0){
				 //查询付款方式
				 SearchConditions scs2 = new SearchConditions();
				 scs2.setRemovedProperty(null);
				 SearchResult result1 = basicModePaymentService.findListByExample(scs2);
				 List<BasicModePaymentDO> mp = result1.getResults();
				 model.addAttribute("payment", mp);
				 model.addAttribute("xx", 1);
			 }
		}
	//	model.addAttribute("companyDOs", companyDOs);
		return EIDT;
	}
	
	@RequestMapping("/griditems")
	public void griditems(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			LogicSkDO lpd =logicSkService.findListById(id);
			List<LogicSkItemDO> skitemlist=logicSkService.findItemListBysoid(lpd.getId());
			OutJsonGrid out = new OutJsonGrid(skitemlist);
			out.printJSon(response);
		}
	}
	
	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicSkDO curAP, BindingResult result, Model model) throws SyBaseException, SyCodeException {
		BodyMsg bodyMap = BodyMsg.getInstance();
		String itemdata = request.getParameter("itemdata");
		String submitFlag = request.getParameter("submitFlag");
		if(itemdata==null&&"".equals(itemdata)){
			bodyMap.isFail();
			bodyMap.configWebInfor("收款单内容不能为空！");
			return bodyMap.modelMap;
		}
		try {
			if("0".equals(submitFlag)){
				curAP.setBillStatus(0);
				curAP.setSkState(0);
				logicSkService.sksave(request, curAP);
			}
			if("1".equals(submitFlag)){
				curAP.setBillStatus(2);
				logicSkService.skcommit(request, curAP);
			}
			
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
			bodyMap.configWebId(curAP.getId());
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
		return bodyMap.modelMap;
	}
	

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String ids = request.getParameter("ids");
			String[] fields=ids.split(",");
			for(String field : fields){
				LogicSkDO ld=logicSkService.findListById(field);
				if(ld.getId()!=null){
					ld.setRemoved(1);
					logicSkService.update(ld,SessionUtil.getUser(request));
				}
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}

	/**
	 * ligerUI树的json
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/tree")
	public void treelist(HttpServletRequest request,HttpServletResponse response)throws Exception{
		JqGridHandler hander=new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		scs.setLimitPage(false);//不分页
		hander.getWheresNotLimit(scs);
		List<BasicCompanyDO> list =basicCompanyService.find(scs);
		AjaxUtil.printJSonArr(response, JSONArray.toJSONString(list));
	}
	
	@RequestMapping(value = "/exportExcel")
	public void printer(HttpServletRequest request, HttpServletResponse response) throws Exception{

		try {
			String id = request.getParameter("id");
			LogicSkDO lsk=new LogicSkDO();
			List<LogicSkItemDO> ls=new ArrayList<LogicSkItemDO>();
			if(!"".equals(id)&&id!=null){
				lsk =logicSkService.findListById(id);
			}
			if(lsk.getId()!=null){
				SearchConditions scs = new SearchConditions();
				scs.addCondition("soid", lsk.getId(),SearchCondition.OP_EQUAL);
				scs.setLimitPage(false);
				scs.setRemovedProperty(null);
				ls =logicSkService.findItemListByExample(scs).getResults();
			}
//			List<Map<String,Object>> dateMapRows = this.getMapDateRows(purOrderItemDAO.getByPOId(id));
//			Map<String,Object> map = this.getMapDate(purOrder);
			if(ls.size()>0){
				request.setAttribute("lsk", lsk);
				request.setAttribute("ls", ls);
				request.setAttribute("row", ls.size());
				request.setAttribute("time", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
				
				response.setContentType("application/vnd.ms-excel");
				response.setHeader("Content-disposition", "attachment;filename=" + lsk.getSkCode() + ".xls");
			
				RequestDispatcher dispatcher = request.getRequestDispatcher("/views/printer/SkPrint.jsp");
			
				dispatcher.forward(request, response);
			}
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}